package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE_KEY;
import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE_TTL;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public List<ShopType> queryShopTypeList() {
        // 1.先从缓存中尝试获取
        List<String> shopTypeList = stringRedisTemplate.opsForList().range(CACHE_SHOP_TYPE_KEY, 0, -1);
        List<ShopType> typeList = new ArrayList<>();
        if (shopTypeList != null && !shopTypeList.isEmpty()) {
            shopTypeList.forEach((shopType) -> {
                ShopType bean = JSONUtil.toBean(shopType, ShopType.class);
                typeList.add(bean);
            });
            // 1.1 返回数据
            return typeList;
        }

        // 2.不存在则查询数据库
        List<ShopType> dbShopTypeList = query().orderByAsc("sort").list();
        if(dbShopTypeList == null || dbShopTypeList.isEmpty()){
            // 2.1 数据库中没有该数据 返回错误null
            return null;
        }
        // 3.缓存数据
        List<String> cacaheShopTypeList = new ArrayList<>();
        dbShopTypeList.forEach(bean -> {
            String jsonStr = JSONUtil.toJsonStr(bean);
            cacaheShopTypeList.add(jsonStr);
        });
        stringRedisTemplate.opsForList().rightPushAll(CACHE_SHOP_TYPE_KEY, cacaheShopTypeList);
        stringRedisTemplate.expire(CACHE_SHOP_TYPE_KEY, CACHE_SHOP_TYPE_TTL, TimeUnit.MINUTES);
        // 4.返回数据
        return dbShopTypeList;
    }
}
